package com.qyhl.webtv.module_live.teletext.detail.popview.detail;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.live.ShoppingListBean;
import com.qyhl.webtv.commonlib.entity.live.ShoppingUserInfoBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_live.R;
import com.qyhl.webtv.module_live.R2;
import com.weavey.loading.lib.LoadingLayout;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;
import razerdp.basepopup.BasePopupWindow;

public class TeleTextShopDetailPopView extends BasePopupWindow implements TeleTextShopDetailContract.TeleTextShopDetailView {
    private Activity mContext;
    private String shopId;
    private View popupView;
    private TextView title;
    private TextView num;
    private TextView score;
    private TextView stock;
    private TextView deadline;
    private TextView address;
    private TextView tips;
    private TextView tipTag;
    private TextView exchangeBtn;
    private RoundedImageView cover;
    private RoundedImageView saleOut;
    private LoadingLayout loadMask;
    private TextView minusBtn;
    private TextView plusBtn;
    private TextView description;

    private ShoppingListBean mBean;

    private ShoppingUserInfoBean userInfoBean;

    private TeleTextShopDetailPresenter mPresenter;

    private LoadingDialog.Builder mBuilder;

    public TeleTextShopDetailPopView(Activity context, String id) {
        super(context);
        mContext = context;
        shopId = id;
        bindEvent(context, id);
    }

    @Override
    protected Animation initShowAnimation() {
        return getTranslateVerticalAnimation(1f, 0, 500);
    }

    @Override
    protected Animation initExitAnimation() {
        return getTranslateVerticalAnimation(0, 1f, 500);
    }

    @Override
    public View getClickToDismissView() {
        return popupView.findViewById(R.id.close_btn);
    }


    @Override
    public View onCreatePopupView() {
        popupView = LayoutInflater.from(getContext()).inflate(R.layout.live_popview_shop_detail, null);
        return popupView;
    }

    @Override
    public View initAnimaView() {
        return popupView.findViewById(R.id.popup_anima);
    }

    private void bindEvent(Activity context, String itemId) {
        mPresenter = new TeleTextShopDetailPresenter(this);
        if (popupView != null) {
            title = popupView.findViewById(R.id.title);
            num = popupView.findViewById(R.id.num);
            score = popupView.findViewById(R.id.score);
            stock = popupView.findViewById(R.id.stock);
            deadline = popupView.findViewById(R.id.deadline);
            address = popupView.findViewById(R.id.address);
            tips = popupView.findViewById(R.id.tips);
            tipTag = popupView.findViewById(R.id.tips_tag);
            exchangeBtn = popupView.findViewById(R.id.exchange_btn);
            cover = popupView.findViewById(R.id.cover);
            saleOut = popupView.findViewById(R.id.sale_out);
            loadMask = popupView.findViewById(R.id.load_mask);
            minusBtn = popupView.findViewById(R.id.minus_btn);
            plusBtn = popupView.findViewById(R.id.plus_btn);
            description = popupView.findViewById(R.id.description);
        }
        loadMask.setStatus(LoadingLayout.Loading);

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(itemId);
            }
        });

        exchangeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            showLoading();
                            String username = CommonUtils.getInstance().getUserName();
                            mPresenter.getUserInfo(username);
                        } else {
                            Toasty.normal(mContext, "尚未登录或登录已失效！").show();
                            RouterManager.routerLogin(mContext, 0);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });
            }
        });


        mPresenter.getDetail(itemId);
    }


    /**
     * 显示加载动画
     */
    protected void showLoading() {
        mBuilder = new LoadingDialog.Builder(mContext, true);
        mBuilder.setCanceledOnTouchOutside(false);
        mBuilder.setCancelable(true);
        mBuilder.show();
    }

    /**
     * 隐藏加载动画
     */
    protected void dismissLoading() {
        if (mBuilder != null) {
            mBuilder.dismiss();
        }
    }

    /**
     * 生成TranslateAnimation
     *
     * @param durationMillis 动画显示时间
     * @param start          初始位置
     */
    private static Animation getTranslateVerticalAnimation(float start, float end, int durationMillis) {
        Animation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, start, Animation.RELATIVE_TO_PARENT, end);
        translateAnimation.setDuration(durationMillis);
        return translateAnimation;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(ShoppingListBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        mBean = bean;

        title.setText(bean.getItemName());
        score.setText(bean.getPrice());
        stock.setText("库存：" + bean.getStock() + "件");

        Glide.with(mContext)
                .load(bean.getItemPic())
                .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                .into(cover);

        deadline.setText(StringUtils.isNotEmpty(bean.getExchangeDeadline()) ? DateUtils.translateToShopping(bean.getExchangeDeadline()) : "不限期");

        if (bean.getShop() != null) {
            address.setText(bean.getShop().getAddress());
        } else {
            address.setText("暂无商铺地址信息");
        }

        description.setText(bean.getItemDesc());

        if (StringUtils.isEmpty(bean.getOtherDesc())) {
            tips.setVisibility(View.GONE);
            tipTag.setVisibility(View.GONE);
        } else {
            tips.setVisibility(View.VISIBLE);
            tipTag.setVisibility(View.VISIBLE);
            tips.setText(bean.getOtherDesc());
        }

        if (bean.getStatus() == 0) {
            if (bean.getStock() == 0) {
                saleOut.setImageResource(R.drawable.shop_sale_out_icon);
                saleOut.setVisibility(View.VISIBLE);
                exchangeBtn.setEnabled(false);
                exchangeBtn.setText("已售罄");
            } else {
                exchangeBtn.setEnabled(true);
                saleOut.setVisibility(View.GONE);
            }
        } else if (bean.getStatus() == 3) {
            saleOut.setImageResource(R.drawable.shop_sale_overdue_icon);
            saleOut.setVisibility(View.VISIBLE);
            exchangeBtn.setEnabled(false);
            exchangeBtn.setText("已过期");
        } else {
            saleOut.setImageResource(R.drawable.shop_sale_off_icon);
            saleOut.setVisibility(View.VISIBLE);
            exchangeBtn.setEnabled(false);
            exchangeBtn.setText("已下架");
        }

    }

    @Override
    public void setError(String msg) {
        dismissLoading();
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        if (!NetUtil.isNetworkAvalible(mContext)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @Override
    public void setStock(int stock) {
        switch (mBean.getPriceType()) {
            case 1://普通积分
                if (userInfoBean.getAppScore() >= Integer.parseInt(mBean.getPrice())) {
                    if (stock <= 0) {
                        dismissLoading();
                        Toasty.normal(mContext, "库存不足！").show();
                        mPresenter.getDetail(shopId);
                    } else {
                        mPresenter.doOrder(CommonUtils.getInstance().getNickName(), CommonUtils.getInstance().getUserName(), shopId, "1");
                    }
                } else {
                    dismissLoading();
                    Toasty.normal(mContext, "积分不足！").show();
                }
                break;
            case 2://志愿者积分
                if (userInfoBean.getCivilizedScore() >= Integer.parseInt(mBean.getPrice())) {
                    if (stock <= 0) {
                        dismissLoading();
                        Toasty.normal(mContext, "库存不足！").show();
                        mPresenter.getDetail(shopId);
                    } else {
                        mPresenter.doOrder(CommonUtils.getInstance().getNickName(), CommonUtils.getInstance().getUserName(), shopId, "1");
                    }
                } else {
                    dismissLoading();
                    Toasty.normal(mContext, "积分不足！").show();
                }
                break;
            case 0:
                dismissLoading();
                Toasty.normal(mContext, "暂无该类型积分！").show();
                break;
        }
    }

    @Override
    public void setUserInfo(ShoppingUserInfoBean bean) {
        userInfoBean = bean;
        if (mBean != null) {
            if (StringUtils.isEmpty(mBean.getExchangeDeadline())) {
                mPresenter.getStock(shopId);
            } else {
                if (DateUtils.isBeforeTime(mBean.getExchangeDeadline())) {
                    mPresenter.getStock(shopId);
                } else {
                    dismissLoading();
                    Toast.makeText(mContext, "兑换时间已截止！", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void orderSuccess(String msg) {
        dismissLoading();
        dismiss();
        new OtherDialog.Builder(mContext)
                .setContentView(R.layout.live_dialog_shop_order_success)
                .setOnClickListener(R.id.check_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", msg);
                        bundle.putString("deadline", StringUtils.isNotEmpty(mBean.getExchangeDeadline()) ? mBean.getExchangeDeadline() : "不限期");
                        bundle.putString("start", mBean.getCreateTime());
                        RouterManager.router(ARouterPathConstant.SHOP_CODE, bundle);
                    }
                })
                .setDismissButton(R.id.cancel_btn)
                .show();

    }

    @Override
    public void orderError(String msg) {
        dismissLoading();
        dismiss();
        new OtherDialog.Builder(mContext)
                .setContentView(R.layout.live_dialog_shop_order_error)
                .setText(R.id.error_msg, msg)
                .setDismissButton(R.id.cancel_btn)
                .show();

    }
}